package com.mobi.Survey;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.mobi.Survey.controller.SurveyDetailPojo;
import com.mobi.Survey.controller.SurveyPojo;
import com.mobi.Survey.controller.SurveyResultPojo;
import com.mobi.Survey.model.AbstractTable;
import com.mobi.Survey.model.SurveyDetailTable;
import com.mobi.Survey.model.SurveyTable;
import com.mobi.Survey.uicomponents.ControlFactory;

/**
 * 
 * <p>
 * <b>Author:</b> Yahya Arshad
 * <p>
 * <b>Company:</b> Mobi Media Soft
 * <p>
 * <b> Website:</b> www.mobimediasoft.com
 * <p>
 * SurveyAnswersScreen.java shows answers screen given by user
 * <p>
 */
public class SurveyAnswersScreen extends AbstractScreen
{

	private Button btnPrevious;
	private Button btnNext;

	private int currentCompIndex = 0;
	private int lastComponent = 0;
	private long surveyId;
	private boolean showAllControls;

	private TextView txtPageNumber;
	private List<View> views = new ArrayList<View>();
	private List<SurveyDetailPojo> sdps;
	private SurveyPojo survey;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		Intent intent = getIntent();

		if (intent != null)
		{
			// get the id of the survey for which we want to show result to user
			// id should be greater than 0
			Bundle bundle = intent.getExtras();
			if (bundle != null)
			{
				surveyId = ((Long) bundle.get("data")).intValue();
				SurveyTable surveyResult = new SurveyTable(this);
				try
				{
					survey = surveyResult.getSurveyForAnswer(this, surveyId);
				} catch (Exception e)
				{
					showShortToast(Messages.NO_ANSWER_DATA);
					finish();
				} finally
				{
					surveyResult.closeDB();
				}

			}

		}
		setTitle(survey.getSurveyDiscription());
		// Background task to retrive answer data from sqlite
		new LongTask().execute(surveyId);
	}

	@Override
	protected void initUiVars()
	{

		// If Survey Screen type is not single screen we have to use display a
		// way to navigate to other input control
		btnNext = (Button) findViewById(R.id.btnNext);
		btnPrevious = (Button) findViewById(R.id.btnPrevious);
		txtPageNumber = (TextView) findViewById(R.id.txtPageNumber);

	}

	@Override
	protected int getLayoutId()
	{

		return LayoutIds.SURVEY_ANSWERS;
	}

	@Override
	public void onBackPressed()
	{

		super.onBackPressed();
		onRelease();
		finish();
	}

	@Override
	protected void onRelease()
	{
		if (null != null)
		{
			sdps.clear();
			sdps = null;
		}
		if (null != views)
		{
			views.clear();
			views = null;

		}
	}

	public void btnClick(View v)
	{

		int id = v.getId();
		// show next control
		if (id == R.id.btnNext)
		{
			onBtnNext();
			// show previous control
		} else if (id == R.id.btnPrevious)
		{
			onBtnPrevious();

		}

	}

	private void onBtnPrevious()
	{
		currentCompIndex--;
		byte reverse = 0;
		refreshButtonsState();
		refreshControlsVisibility(reverse);
		if (!showAllControls)
		{
			StringBuilder sbTxtPageNumber = new StringBuilder();

			sbTxtPageNumber.append("(");
			sbTxtPageNumber.append(currentCompIndex + 1);
			sbTxtPageNumber.append(" of ");
			sbTxtPageNumber.append(lastComponent + 1);
			sbTxtPageNumber.append(")");
			txtPageNumber.setText(sbTxtPageNumber.toString());
		}

	}

	private void onBtnNext()
	{
		currentCompIndex++;
		byte forward = 1;
		refreshButtonsState();
		refreshControlsVisibility(forward);

		if (!showAllControls)
		{
			StringBuilder sbTxtPageNumber = new StringBuilder();

			sbTxtPageNumber.append("(");
			sbTxtPageNumber.append(currentCompIndex + 1);
			sbTxtPageNumber.append(" of ");
			sbTxtPageNumber.append(lastComponent + 1);
			sbTxtPageNumber.append(")");

			txtPageNumber.setText(sbTxtPageNumber.toString());
		}

	}

	/**
	 * Once user clicks next or previous button we may need to enable or disable
	 * previous or next button once we reach first or last control
	 */
	private void refreshControlsVisibility(byte direction)
	{

		if (direction == 1)
		{
			views.get(currentCompIndex).setVisibility(View.VISIBLE);
			if (currentCompIndex >= 0)
			{
				views.get(currentCompIndex - 1).setVisibility(View.GONE);

			}
		} else
		{
			views.get(currentCompIndex).setVisibility(View.VISIBLE);
			if (currentCompIndex >= 0)
			{
				views.get(currentCompIndex + 1).setVisibility(View.GONE);
			}
		}

	}

	/**
	 * Create screen controls dynamically on the base of survey detail data and
	 * user answer we are not creating {@link ControlFactory#CONTROL_IMAGE_VIEW}
	 * {@link ControlFactory#CONTROL_VIDEO_VIEW}
	 * {@link ControlFactory#CONTROL_TYPE_ZERO}
	 * {@link ControlFactory#CONTROL_URL} because these control don't have any
	 * answer
	 */
	private void createViews()
	{
		showAllControls = survey.isShowAllControls();

		ViewGroup vg = (ViewGroup) findViewById(R.id.llSurveyDetailSingle);

		if (vg != null && sdps != null && sdps.size() > 0)
		{

			for (SurveyDetailPojo sdp : sdps)
			{

				if (sdp.getControlType() == ControlFactory.CONTROL_IMAGE_VIEW
						|| sdp.getControlType() == ControlFactory.CONTROL_VIDEO_VIEW
						|| sdp.getControlType() == ControlFactory.CONTROL_TYPE_ZERO
						|| sdp.getControlType() == ControlFactory.CONTROL_URL)
					continue;
				View v = ControlFactory.createControlForAnswerScreen(sdp, this,
						showAllControls);
				vg.addView(v);

				if (showAllControls)
				{

					views.add(v);

				} else
				{

					views.add(v);
					v.setVisibility(View.GONE);

				}

			}
			lastComponent = views.size() - 1;
			if (showAllControls)
			{

				btnNext.setVisibility(View.GONE);
				btnPrevious.setVisibility(View.GONE);
				txtPageNumber.setVisibility(View.GONE);

			} else
			{

				// because it is single component per screen we are making first
				// item visible
				views.get(0).setVisibility(View.VISIBLE);

				refreshButtonsState();

				// setting current page number of total page
				StringBuilder sbTxtPageNumber = new StringBuilder();
				sbTxtPageNumber.append("(");
				sbTxtPageNumber.append(currentCompIndex + 1);
				sbTxtPageNumber.append(" of ");
				sbTxtPageNumber.append(lastComponent + 1);
				sbTxtPageNumber.append(")");
				txtPageNumber.setText(sbTxtPageNumber.toString());
			}

		} else
		{
			// printMessage("View Group Null Include header");
			showShortToast(Messages.NO_SURVEY_DETAIL);
		}
	}

	/**
	 * refreshes button state on each next and previous action
	 */
	private void refreshButtonsState()
	{
		if (currentCompIndex == 0)
		{
			btnPrevious.setEnabled(false);
		}
		if (currentCompIndex == lastComponent)
		{
			btnNext.setEnabled(false);

		}
		if (currentCompIndex > 0)
		{
			btnPrevious.setEnabled(true);
		}
		if (currentCompIndex < lastComponent)
		{
			btnNext.setEnabled(true);
		}

	}

	/**
	 * 
	 * @author Yahya Arshad Retrive control data for answer screen in background
	 *         after retriving data we call
	 *         {@link SurveyAnswersScreen#createViews()}
	 */
	private class LongTask extends AsyncTask<Long, Integer, Object>
	{
		ProgressDialog progressDialog = null;

		protected Object doInBackground(Long... params)
		{
			long surveyId = params[0];
			AbstractTable at = new SurveyDetailTable(SurveyAnswersScreen.this);
			sdps = ((SurveyDetailTable) at).getSurveyDetailForAnswer(surveyId);
			at.closeDB();
			SurveyResultPojo.writeSurveyResult(surveyId, sdps,
					SurveyAnswersScreen.this);

			return null;

		}

		protected void onPostExecute(Object result)
		{

			super.onPostExecute(result);
			createViews();
			progressDialog.dismiss();
			progressDialog = null;

		}

		protected void onPreExecute()
		{
			super.onPreExecute();
			try
			{
				progressDialog = ProgressDialog.show(SurveyAnswersScreen.this,
						"", Messages.FETCHING_SURVEY_DETAIL);
			} catch (Exception e)
			{
				e.printStackTrace();
			}

		}

	}

}
